package com.homelock.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * spring异步任务的线程池自定义配置 <br>
 * 该线程池被所有的异步任务共享，而不属于某一个异步任务 <br>
 * @Author zoumy
 * @CreateDate 2018/1/25 上午9:00
 */
@Configuration
public class AsyncTaskExecutePool implements AsyncConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(AsyncTaskExecutePool.class);
    /**
     * 线程池维护线程的核心线程池数
     */
    @Value("${spring.task.pool.corePoolSize}")
    private int corePoolSize;
    /**
     * 线程池维护线程的最大数量
     */
    @Value("${spring.task.pool.maxPoolSize}")
    private int maxPoolSize;
    /**
     * 线程池维护线程所允许的空闲时间
     */
    @Value("${spring.task.pool.keepAliveSeconds}")
    private int keepAliveSeconds;
    /**
     * 线程池所使用的缓冲队列
     */
    @Value("${spring.task.pool.queueCapacity}")
    private int queueCapacity;

    @Bean("asyncTaskExecute")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix("asyncTaskExecutor-");
        /**
         *  rejection-policy：当pool已经达到max size的时候，如何处理新任务
         *  CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 异步任务异常处理
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                logger.error("异步线程池任务发生异常，exception method:"+method.getName());
                logger.error("异常信息：{}", ex.getMessage());
            }
        };
    }
}
